/**
 * Created by gouyuheng on 2017/2/17.
 */
import $ from 'jquery'
import Vue from 'vue'
import {API_ROOT} from '../config.js'
Vue.prototype.weixin = function (url, link) {
  let logo = window.sessionStorage.getItem('LOGO')
  Vue.wechat.ready(function () {
    Vue.wechat.onMenuShareAppMessage({
      title: '孝行通孝心商城', // 分享标题
      desc: '一个让子女为父母尽孝的老年服务平台', // 分享描述
      link: link, // 分享链接
      imgUrl: logo, // 分享图标
      success: function () {
        // 用户确认分享后执行的回调函数
      },
      cancel: function () {
        // 用户取消分享后执行的回调函数
      }
    })
    Vue.wechat.onMenuShareTimeline({
      title: '孝行通孝心商城', // 分享标题
      link: link, // 分享链接
      imgUrl: logo, // 分享图标
      success: function () {
        // 用户确认分享后执行的回调函数
      },
      cancel: function () {
        // 用户取消分享后执行的回调函数
      }
    })
  })
  $.ajax({
    url: API_ROOT + '/api/wxAuth/jsauth?url=' + encodeURIComponent(url + '/static/index.html'),
    type: 'post',
    success: function (t) {
      if (t.status === 100) {
        let sign = t.data.sign
        let weixinConfig = {
          debug: false,
          appId: sign.appId,
          timestamp: sign.timeStamp,
          nonceStr: sign.nonceStr,
          signature: sign.signature,
          jsApiList: ['onMenuShareAppMessage', 'chooseWXPay', 'onMenuShareTimeline']
        }
        // 授权
        Vue.wechat.config(weixinConfig)
        // 调用ready初始化
      } else {
        Vue.prototype.weixin()
      }
    },
    error: function (t) {
      Vue.prototype.weixin()
    }
  })
}

Vue.prototype.reloadPage = function (name) {
  let u = navigator.userAgent
  // android设备
  if (u.indexOf('Android') > -1 || u.indexOf('Adr') > -1) {
    return
  }
  let refreshed = window.sessionStorage.getItem(name)
  if (refreshed === '' || refreshed === undefined || refreshed === null) {
    refreshed = 0
  }
  if (refreshed === 0) {
    window.sessionStorage.setItem(name, 1)
    window.location.reload()
  }
}

Vue.prototype.http = function (url, data, success, error) {
  $.ajax({
    url: API_ROOT + url,
    type: 'post',
    data: JSON.stringify(data),
    success: success,
    dataType: 'json',
    contentType: 'application/json;charset=utf-8',
    error: error
  })
}

const wx = require('weixin-js-sdk')
const plugin = {
  install (Vue) {
    Vue.prototype.$wechat = wx
    Vue.wechat = wx
  },
  $wechat: wx
}

export default plugin
export const install = plugin.install
